const Service = require('egg').Service;
const Officegen = require('officegen');
const fs = require('fs');
const uuid = require('node-uuid');
class OfficegenService extends Service {

    async memoir(temp_id, filename) {
        const { ctx, config } = this;
        //生成文件夹
        let ufolder = await ctx.service.md5.cryptoPassFunc(uuid.v1() + new Date().getTime());
        let retPath = `/public/template/${ufolder}/个人自传.docx`
        let orgpath = config.baseDir + 'app' + retPath;
        let contentData = await ctx.model.HrbeuWinter.findOne({ where: { temp_id } });
        await ctx.service.fs.createFolder(orgpath);
        return new Promise((resolve, reject) => {
            const docxMap = {
                winp_01: "求学履历表",
                winp_02: "个人成长环境分析",
                winp_03: "父母、老师、好友的评价",
                winp_04: "最自豪或最引以为傲的两件事",
                winp_05: "最欣赏的两个人",
                winp_06: "本学期学习感受",
                winp_07: "本学期成长收获",
                winp_08: "自己理想的职业",
                winp_09: "给辅导员的一封信",
                winp_10: "送给此时此刻的自己一句话",
                winp_11: "自拟题目"
            };
            let out = fs.createWriteStream(orgpath); // 创建文件
            let docx = Officegen('docx');
            docx.on('finalize', function (written) {
                // resolve(orgpath);
            })
            docx.on('error', function (err) {
                reject(err);
            })
            for (let key in docxMap) {//遍历json对象的每个key/value对,p为key
                let pObj = docx.createP({ align: 'center' });
                pObj.addText(docxMap[key], { font_size: 14, bold: true });
                pObj = docx.createP({ align: 'left' });
                if (contentData[key]) {
                    let textArr = (contentData[key] || "").split(/[\n,]/g);
                    for (var i = 0; i < textArr.length; i++) {
                        pObj.addText(textArr[i], { font_size: 10 });
                        if((i+1)<textArr.length){
                            pObj.addLineBreak();//换行
                        }
                    }
                }
                docx.putPageBreak()//换页
            }
            docx.generate(out);
            out.on('finish', () => {
                console.log("写入完成");
                setTimeout(() => {
                    //暂存30分钟，30分钟后自动删除
                    ctx.service.fs.delPath(orgpath);
                }, 1000 * 60 * 30)
                resolve(retPath);
            });
        });
    }

}

module.exports = OfficegenService;
